import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Button, Form, Input, Select, Table, Space } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { SearchOutlined } from '@ant-design/icons'
// 引入ts数据类型
import {
  IhospitalList,
  IhospitalItem,
  IprovinceList,
} from '@api/hospital/hospitalList/model/hospitalListTypes'
// 引入发送请求的函数
import {
  reqHospitalList,
  reqProvince,
  reqCityOrDistrict,
} from '@api/hospital/hospitalList'
const { Option } = Select //注意: Option是从Select解构出来的

let flag = false // 如果flag为true,则添加筛选条件. 如果flag是false则不添加筛选条件
export default function HospitalList() {
  // 存储表格数据的状态
  const [hospitalList, setHospitalList] = useState<IhospitalList>([])
  // 分页的状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)

  // 省数据的状态
  const [province, setProvince] = useState<IprovinceList>([])
  // 市数据的状态
  const [city, setCity] = useState<IprovinceList>([])
  // 区数据的状态
  const [district, setDistrict] = useState<IprovinceList>([])
  // 医院类型
  const [hospitalType, setHospitalType] = useState<IprovinceList>([])

  // 创建form实例
  const [form] = Form.useForm()

  // 编程式导航
  const navigate = useNavigate()

  useEffect(() => {
    // 医院列表一打开页面就要获取表格数据
    getHospitalList(page, pageSize)
    // 获取省数据
    getProvince()

    // 获取医院状态
    getHospitalType()
  }, [])

  // 获取医院列表表格数据的函数
  async function getHospitalList(page: number, pageSize: number) {
    let result
    if (flag) {
      // 有筛选条件
      // 筛选条件的数据,在form表单中
      const params = form.getFieldsValue()
      // 由于表单中表单项的name和要上传数据的属性一致,所以可以直接展示传递
      result = await reqHospitalList({ page, pageSize, ...params })
    } else {
      // 没有筛选条件
      result = await reqHospitalList({ page, pageSize })
    }

    // console.log(result)
    setHospitalList(result.content)
    setTotal(result.totalElements)
  }

  // 获取省数据
  async function getProvince() {
    const result = await reqProvince()
    setProvince(result)
  }

  // 获取市数据
  async function getCity(parentId: string) {
    const result = await reqCityOrDistrict(parentId)
    // console.log(result)
    setCity(result)
  }

  // 获取区数据
  async function getDistrict(parentId: string) {
    const result = await reqCityOrDistrict(parentId)
    // console.log(result)
    setDistrict(result)
  }

  // 获取医院类型
  async function getHospitalType() {
    const result = await reqCityOrDistrict('10000')
    // console.log(result)
    setHospitalType(result)
  }

  // 查询按钮的事件处理函数
  const onFinish = () => {
    flag = true
    getHospitalList(1, pageSize)
    setPage(1)
  }

  const columns: ColumnsType<IhospitalItem> = [
    {
      title: '序号',
      render(_: any, records: any, index: number) {
        return index + 1
      },
      align: 'center',
    },
    {
      title: '医院logo',
      render(_: any, records: any, index: number) {
        return (
          <img src={'data:image/png;base64,' + _.logoData} alt="" width={80} />
        )
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      dataIndex: 'param',
      render(_) {
        return _.hostypeString
      },
    },
    {
      title: '详细地址',
      dataIndex: 'param',
      render(_) {
        return _.fullAddress
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status === 1 ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render(_) {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                navigate('/syt/hospital/hospitalList/show', {
                  state: _.id,
                })
              }}
            >
              查看
            </Button>
            <Button type="primary">排班</Button>
            <Button type="primary">{_.status === 1 ? '下线' : '上线'}</Button>
          </Space>
        )
      },
      align: 'center',
    },
  ]
  return (
    <Card>
      <Form layout="inline" form={form} onFinish={onFinish}>
        <Form.Item name="provinceCode" style={{ width: 180 }}>
          {/* 注意: defaultValue是用于第一次打开页面,选择默认的选项. 但是如果选项要改变,则defaultValue就无效了. 正常应该使用value */}
          <Select
            placeholder="请选择省"
            onChange={(value) => {
              // 当选择了当前下拉框中的某个选项的时候,会触发
              // console.log(value) // value就是选中的Option的value值(也就是省的编码)
              getCity(value)
              // 清空市和区选中的数据
              form.setFieldsValue({
                cityCode: undefined,
                districtCode: undefined,
              })
            }}
          >
            {province.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
            {/* <Option value="gd">广东</Option>
            <Option value="bj">北京</Option> */}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode" style={{ width: 180 }}>
          <Select
            placeholder="请选择市"
            onChange={(value: string) => {
              //value是市编码
              getDistrict(value)

              // 清空区选择的数据
              form.setFieldsValue({ districtCode: undefined })
            }}
          >
            {city.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
            {/* <Option>深圳</Option>
            <Option>广州</Option> */}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode" style={{ width: 180 }}>
          <Select placeholder="请选择区">
            {district.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
            {/* <Option>宝安区</Option>
            <Option>南山区</Option> */}
          </Select>
        </Form.Item>
        <Form.Item name="hosname" style={{ width: 180 }}>
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode" style={{ width: 180 }}>
          <Input placeholder="医院编码"></Input>
        </Form.Item>
        <Form.Item name="hostype" style={{ width: 180, marginTop: 20 }}>
          <Select placeholder="医院类型">
            {hospitalType.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status" style={{ width: 180, marginTop: 20 }}>
          <Select placeholder="医院状态">
            <Option value={1} key={1}>
              已上线
            </Option>
            <Option value={0} key={0}>
              未上线
            </Option>
          </Select>
        </Form.Item>
        <Form.Item style={{ marginTop: 20 }}>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>

        <Form.Item style={{ marginTop: 20 }}>
          <Button
            onClick={() => {
              // 将flag设置为false
              flag = false
              // 获取没有筛选条件的数据
              getHospitalList(1, pageSize)
              setPage(1)
              // 清空表单中所有的数据
              form.resetFields() //重置表单
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>

      <Table
        rowKey={'id'}
        columns={columns}
        dataSource={hospitalList}
        style={{ marginTop: 20 }}
        bordered
        pagination={{
          current: page,
          pageSize,
          total,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10],
          showTotal(total) {
            return `总共${total}条`
          },
          onChange(page, pageSize) {
            setPage(page)
            setPageSize(pageSize)
            getHospitalList(page, pageSize)
          },
        }}
      ></Table>
    </Card>
  )
}
